import React, { FC } from "react"
import { DndContext, closestCenter, useSensor, useSensors, DragEndEvent, MouseSensor } from "@dnd-kit/core"
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable"

type PropsType = {
    children: JSX.Element | JSX.Element[]
    items: Array<{ id: string; [key: string]: any }>
    onDragEnd: (oldIndex: number, newIndex: number) => void
}

const SortableContainer: FC<PropsType> = (props: PropsType) => {
    // children是一个子组件，类似于vue中的slot
    const { children, items, onDragEnd } = props

    const sensors = useSensors(
        useSensor(MouseSensor, {
            // 活动限制：鼠标拖拽超过了8个像素 才判定为拖拽
            activationConstraint: {
                distance: 8 // 8px
            }
        })
    )

    function handleDragEnd(event: DragEndEvent) {
        const { active, over } = event
        if (over == null) return

        if (active.id !== over.id) {
            const oldIndex = items.findIndex(c => c.fe_id === active.id)
            const newIndex = items.findIndex(c => c.fe_id === over.id)
            onDragEnd(oldIndex, newIndex)
        }
    }
    return (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
            <SortableContext items={items} strategy={verticalListSortingStrategy}>
                {children}
            </SortableContext>
        </DndContext>
    )
}

export default SortableContainer
